package com.gs.thunder.web.controller;

import com.gs.thunder.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: Legolas
 * Date: 2017/12/20 0020
 */
@Controller
@RequestMapping("test")
public class IndexController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("upload")
    public String uploadView(){
        return "upload";
    }


    @RequestMapping("uploadfile")
    public String oneFileUpload(@RequestParam("file")CommonsMultipartFile files[], HttpServletRequest request, ModelMap model){

        List<String> list = new ArrayList<>();

        //上传位置
        String path = Constant.UPLOADFILE;//设定文件保存的目录

        File f = new File(path);
        if(!f.exists())
            f.mkdirs();

        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            System.out.println("原始文件名："+fileName);
            String newFileName = UUID.randomUUID() + fileName ;
            if(!files[i].isEmpty()){
                try{
                    FileOutputStream fos = new FileOutputStream(path+newFileName);
                    InputStream in = files[i].getInputStream();
                    int b = 0;
                    while((b = in.read())!=-1){
                        fos.write(b);
                    }
                    fos.close();
                    in.close();
                }
                catch(Exception e){
                    logger.info("文件上传失败->{}",e.getMessage());
                }
            }
            System.out.println("上传文件到:" + path + newFileName);
            // 保存文件地址
            list.add(path + newFileName);

        }

        model.addAttribute("fileList", list);
        return "success";

    }

}
